package com.frost.book.controller;

import com.frost.book.constant.Constant;
import com.frost.book.model.UserInfo;
import com.frost.book.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {
//    @RequestMapping("/login")
//    public boolean login(String username, String password, HttpSession session) {
//        // 校验参数
//        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
//            return false;
//        }
//        // 校验密码
//        if ("admin".equals(username) && "123456".equals(password)) {
//            session.setAttribute("username", username);
//            session.setAttribute("password", password);
//            return true;
//        }
//
//        return false;
//    }

    // 修改后
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public boolean login(@RequestParam("userName") String userName, String password, HttpSession session) {
        // 校验参数
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            return false;
        }
        // 校验密码
        UserInfo userInfo = userService.queryByName(userName);
        if (userInfo == null) {
            return false;
        }
        if (password.equals(userInfo.getPassword())) {
            userInfo.setPassword("");
            session.setAttribute(Constant.USER_SESSION_KEY, userInfo);
            return true;
        }

        return false;
    }

}
